package org.example.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpVersion;

/**
 * 服务处理器
 */
public class ServerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) {
        if (msg instanceof HttpRequest) {
            //排除网站图标获取
            if ("/favicon.ico".equals(((HttpRequest) msg).uri())) {
                return;
            }
            System.out.println("消息类型:" + msg.getClass());
            System.out.println("客户端地址:" + ctx.channel().remoteAddress());
            //创建回答缓冲区
            ByteBuf byteBuf = Unpooled.copiedBuffer("你好".getBytes());
            //构建response
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
                    HttpResponseStatus.OK, byteBuf);
            //设置响应头
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plan;charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, byteBuf.readableBytes());
            //推送消息
            ctx.writeAndFlush(response);
        }
    }
}
